package com.are.inventario;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;

public class ClienteActivity extends Activity {

	private TextView nic, nis, nif, medidor, direccion,marca;
	private TextView longitud, latitud;
	private String url;
	private String parametros;
	
	private static final int INTENT_ID_GPS = 100;
	private static final int INTENT_ID_ANOMALIA = 101;
	
	private EditText trafo,matricula, nif_anterior, nif_posterior, anomalia, observacion;
	
	private ProgressDialog progressDialog;
	private String ReceiveServer = "";
	
	private final Handler progressHandler = new Handler() {

		public void handleMessage(Message msg) {
			if (msg.obj != null) {
				ReceiveServer = (String) msg.obj;
				ShowMensaje(ReceiveServer);
			}
			progressDialog.dismiss();
		}
	};
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cliente);
        Bundle extras = getIntent().getExtras();
        nic = (TextView)findViewById(R.id.txtNic);
        nis = (TextView)findViewById(R.id.txtNis);
        nif = (TextView)findViewById(R.id.txtNif);
        medidor = (TextView)findViewById(R.id.txtMedidor);
        direccion = (TextView)findViewById(R.id.txtDireccion);
        marca = (TextView)findViewById(R.id.txtMarca);
        nic.setText(extras.getString("nic"));
        nis.setText(extras.getString("nis"));
        nif.setText(extras.getString("nif"));
        direccion.setText(extras.getString("direccion"));
        medidor.setText(extras.getString("medidor"));
        marca.setText(extras.getString("marca"));
        
        latitud = (TextView)findViewById(R.id.lbLatitud);
        longitud = (TextView)findViewById(R.id.lbLongitud);
        
        trafo = (EditText)findViewById(R.id.txtTrafo);
        matricula = (EditText)findViewById(R.id.txtMatricula);
        nif_anterior = (EditText)findViewById(R.id.txt_nif_anterior);
        nif_posterior = (EditText)findViewById(R.id.txt_nif_posterior);
        anomalia = (EditText)findViewById(R.id.txt_anomalia);
        anomalia.setEnabled(false);
        observacion = (EditText)findViewById(R.id.txt_observacion);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_cliente, menu);
        return true;
    }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.menu_enviar:
			SendData();
			break;
		case R.id.menu_gps:
			startActivityForResult(new Intent(this, GPSActivity.class),INTENT_ID_GPS);
			break;
		case R.id.menu_anomalia:

			startActivityForResult(new Intent(this, AnomaliaActivity.class),INTENT_ID_ANOMALIA);
			
			break;
		case R.id.menu_cancelar:
			finish();
			break;

		}

		return true;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch(requestCode) {
			case INTENT_ID_GPS:  // obtener la informacion del GPS
				latitud.setText(data.getStringExtra("latitud"));
				longitud.setText(data.getStringExtra("longitud"));
				break;
			case INTENT_ID_ANOMALIA:  // obtener la informacion del GPS
				anomalia.setText(data.getStringExtra("codigo"));
				break;
			
			}
		}
		
	}
    
	private void SendData() {
		String strMedidor = medidor.getText().toString();
		String strTrafo = trafo.getText().toString();
		String strMatricula = matricula.getText().toString();
		String strNif_anterior = nif_anterior.getText().toString();
		String strNif_posterior = nif_posterior.getText().toString();
		String strAnomalia = anomalia.getText().toString(); 
		String strObservacion = observacion.getText().toString();
		String strLongitud = longitud.getText().toString();
		String strLatitud = latitud.getText().toString();
		
		if ( strTrafo.equals("") || strMatricula.equals("") || strNif_anterior.equals("") || strNif_posterior.equals("") 
				|| strAnomalia.equals("") || strObservacion.equals("") || strLongitud.equals("0") 
				|| strLatitud.equals("0") ) {
			AlertDialog alert =  (AlertDialog) this.crearDialogoAlerta("Falta Informacion, verifique porfavor");
			alert.show();
			return;
		}
		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String imei = tm.getDeviceId();
        
		try {
			parametros =   URLEncoder.encode("medidor", "ISO-8859-1") + "=" + URLEncoder.encode(strMedidor, "ISO-8859-1");
			parametros +=  "&" + URLEncoder.encode("trafo", "ISO-8859-1") + "=" + URLEncoder.encode(strTrafo, "ISO-8859-1");
			parametros +=  "&" + URLEncoder.encode("matricula", "ISO-8859-1") + "=" + URLEncoder.encode(strMatricula, "ISO-8859-1");
			parametros +=  "&" + URLEncoder.encode("nif_anterior", "ISO-8859-1") + "=" + URLEncoder.encode(strNif_anterior, "ISO-8859-1");
			parametros +=  "&" + URLEncoder.encode("nif_posterior", "ISO-8859-1") + "=" + URLEncoder.encode(strNif_posterior, "ISO-8859-1");
			parametros +=  "&" + URLEncoder.encode("anomalia", "ISO-8859-1") + "=" + URLEncoder.encode(strAnomalia, "ISO-8859-1");
			parametros +=  "&" + URLEncoder.encode("observacion", "ISO-8859-1") + "=" + URLEncoder.encode(strObservacion, "ISO-8859-1");
			parametros +=  "&" + URLEncoder.encode("longitud", "ISO-8859-1") + "=" + URLEncoder.encode(strLongitud, "ISO-8859-1");
			parametros +=  "&" + URLEncoder.encode("latitud", "ISO-8859-1") + "=" + URLEncoder.encode(strLatitud, "ISO-8859-1");
			parametros +=  "&" + URLEncoder.encode("imei", "ISO-8859-1") + "=" + URLEncoder.encode(imei, "ISO-8859-1");
			System.out.println(parametros);
			LoadData();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			AlertDialog alert =  (AlertDialog) this.crearDialogoAlerta(e.getMessage());
			alert.show();
		}
	}
	
	private Dialog crearDialogoAlerta(String mensaje) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Informacion");
		builder.setMessage(mensaje);
		builder.setCancelable(false);
		builder.setPositiveButton("OK", new android.content.DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
		});		
		return builder.create();
	}
	private void LoadData() {
		progressDialog = ProgressDialog.show(ClienteActivity.this, "",
				"Por favor espere mientras se envian los datos...", true);

		this.url = "http://siscos.fcr.com.co:8080/AreApp/SrvClientes?operacion=update";
		new Thread(new Runnable() {
			public void run() {
				HttpConection conn = new HttpConection(url,parametros);
				Message msg = progressHandler.obtainMessage();
				msg.obj = conn.Send();
				progressHandler.sendMessage(msg);
			}
		}).start();
	}
	
	private void ShowMensaje(String data) {
		if (data.equals("OK")) {
			AlertDialog alert =  (AlertDialog) this.crearDialogoAlerta("Cliente actualizado correctamente");
			alert.show();
			finish();
		} else { // error al confirmar la orden
			AlertDialog alert =  (AlertDialog) this.crearDialogoAlerta(data);
			alert.show();
		}

	}
}
